package com.note.chh.notebook.UI.enjoy;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.MotionEvent;
import android.view.View;

import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.note.chh.notebook.Adapter.BeautifulPictureAdapter;
import com.note.chh.notebook.Api.Constant;
import com.note.chh.notebook.Model.BeautifulPictureModel;
import com.note.chh.notebook.R;
import com.note.chh.notebook.UI.base.BaseActivity;
import com.note.chh.notebook.Uitls.ItemDivider;
import com.note.chh.notebook.Uitls.gson.GsonImpl;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;

//美图
public class BeautifulPictureActivity extends BaseActivity {


    @BindView(R.id.topbar)
    QMUITopBar topbar;
    @BindView(R.id.mRecycle_view)
    RecyclerView mRecycleView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private BaseQuickAdapter beautifulAdapter;
    private int pagerIndex = 1, pagerSize = 10;

    @Override
    protected int bindLayout() {
        return R.layout.activity_beautiful_picture;
    }

    @Override
    public void initTopBar() {
        super.initTopBar();
        topbar.setBackgroundColor(getResources().getColor(R.color.app_color_blue));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        topbar.setTitle(getResources().getString(R.string.beautiful));
    }

    @Override
    public void initView() {
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecycleView.setLayoutManager(staggeredGridLayoutManager);
//        staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
////        防止item 交换位置
//        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                staggeredGridLayoutManager.invalidateSpanAssignments(); //防止第一行到顶部有空白区域
//            }
//        });
        mRecycleView.addItemDecoration(new ItemDivider().setDividerWith(SizeUtils.dp2px(5)).setDividerColor(getResources().getColor(R.color.white)));
        beautifulAdapter = new BeautifulPictureAdapter(R.layout.item_beautiful);
        beautifulAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycleView.setAdapter(beautifulAdapter);
        //打开自动加载
        beautifulAdapter.setEnableLoadMore(true);


        //解决swipelayout与Recyclerview的冲突
        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int[] positions = staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(null);
                if (positions[0]==0) {
                    refreshLayout.setEnabled(true);
                }
            }
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
        mRecycleView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action){
                    case MotionEvent.ACTION_DOWN://0
                        break;
                    case MotionEvent.ACTION_MOVE://2
                        //获取第一个完全显示的条目索引 positions[0]
                        int[] positions = staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(null);
                        //达到这个条件就说明滑到了顶部
                        if(positions[0]==0){
                            refreshLayout.setEnabled(true);
                        }else{
                            refreshLayout.setEnabled(false);
                        }
                        break;
                    case MotionEvent.ACTION_UP://1
                        break;
                }
                return false;
            }
        });
    }


    @Override
    public void initListener() {
        super.initListener();
        beautifulAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BeautifulPictureModel.ResultsBean bean = (BeautifulPictureModel.ResultsBean) adapter.getData().get(position);
                Intent intent = new Intent(BeautifulPictureActivity.this, CheckMusicPictureActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("picUrl", bean.getUrl());
                bundle.putString("picName", "/" + bean.get_id() + ".png");
                bundle.putString("picFolder", Constant.girlImageSaveFolder);
                intent.putExtras(bundle);
//            startActivity(CheckMusicPictureActivity.class,bundle);
                startActivity(intent);
                overridePendingTransition(R.anim.scale_in, R.anim.alpha_out);
            }
        });
        beautifulAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                pagerIndex++;
                getBPlist();
            }
        }, mRecycleView);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pagerIndex = 1;
                getBPlist();
            }
        });
    }

    @Override
    public void initData() {
        refreshLayout.autoRefresh();//第一次进入触发自动刷新
//        getBPlist();
    }

    private void getBPlist() {
        OkGo.<String>get("http://gank.io/api/data/福利/" + pagerSize + "/" + pagerIndex)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

//                UserUtil.dLog(" response = "+response.body());
                        BeautifulPictureModel beautifulPictureModel = GsonImpl.get().toObject(response.body(), BeautifulPictureModel.class);
                        List<BeautifulPictureModel.ResultsBean> results = beautifulPictureModel.getResults();
                        if (pagerIndex == 1) {//刷新
                            beautifulAdapter.setNewData(results);
                            refreshLayout.finishRefresh();
                        } else {//加载
                            beautifulAdapter.addData(results);
                            if (results.size() == pagerSize) {
                                beautifulAdapter.loadMoreComplete();//还有下页数据
                            } else {
                                beautifulAdapter.loadMoreEnd();//加载结束，无下页数据
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (pagerIndex == 1) {
                            refreshLayout.finishRefresh();
                        }else{
                            beautifulAdapter.loadMoreFail();//加载失败
                        }
                    }
                });
    }
}
